import React, { useRef, useState } from 'react';
import { Document, Page, pdfjs } from 'react-pdf';
import 'react-pdf/dist/Page/AnnotationLayer.css';
import 'react-pdf/dist/Page/TextLayer.css';
import pdf from './JavaScript.pdf';

pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/legacy/build/pdf.worker.min.js`;

interface Props {
    fileUrl: string;
}

function FilePDF({ fileUrl }: Props) {
    const documentRef = useRef<HTMLDivElement>();
    const scale = useRef(1);
    const [pageNumber, setPageNumber] = useState<number>(1);

    const renderDocumentPage = (num: number, total: number) => {
        if (num <= total) {
            setPageNumber(num);
            requestIdleCallback(() => renderDocumentPage(num + 1, total));
        }
    };

    const onDocumentLoadSuccess = ({ numPages, ...rest }: { numPages: number }) => {
        requestIdleCallback(() => renderDocumentPage(1, numPages));
    };

    return (
        <div className='flex h-screen w-full justify-center overflow-auto rounded-lg bg-[#525659]'>
            <Document
                ref={documentRef}
                file={fileUrl}
                onLoadSuccess={onDocumentLoadSuccess}
                loading='努力加载中...'
                renderMode='canvas'
            >
                {Array.from({ length: pageNumber }).map((_, i: number) => (
                    <Page key={i} pageNumber={i + 1} className='mt-6' loading='努力加载中...' />
                ))}
            </Document>
        </div>
    );
}

export default function ReactPdfPage() {
    return <FilePDF fileUrl={pdf} />;
}
